﻿namespace EFS.RC.Survey.Controls
{
	public partial class Survey : EFS.RC.Survey.Controls.Control
	{
		#region Delegates
		/// Save
		public delegate void SaveCompletedDelegate(System.Int32 surveySessionId);
		public SaveCompletedDelegate OnSaveCompleted = null;

		public delegate void CancelDelegate();
		public CancelDelegate OnCancel = null;

		public delegate void AverageChange(System.Double s);
		public AverageChange OnAverageChange;



		#endregion

		#region Constructors
		/// Implicit
		public Survey()
		{
			//this.stackPanelCategories.Children.Add
			InitializeComponent();


			// do not use programatically
			ConstructorNotAllowed();
			//register_AnswerClick();

		}

		/// Explicit
		public Survey(
			EFS.RC.CC.CH.Entities.Surveys.SurveyInfo surveyObj,
			System.Guid conversationGuid)
		{
			// check
			EFS.Common.Verify.Reference(surveyObj, "surveyObj");

			// init
			InitializeComponent();

			// register events
			UtilitiesService.SurveyCategory_GetBySurveyIDCompleted += new System.EventHandler<Utilities.SurveyCategory_GetBySurveyIDCompletedEventArgs>(UtilitiesService_SurveyCategory_GetBySurveyIDCompleted);
			UtilitiesService.SurveySessionData_CreateCompleted += new System.EventHandler<Utilities.SurveySessionData_CreateCompletedEventArgs>(UtilitiesService_SurveySessionData_CreateCompleted);
			UtilitiesService.SurveySessionData_UpdateCompleted += new System.EventHandler<Utilities.SurveySessionData_UpdateCompletedEventArgs>(UtilitiesService_SurveySessionData_UpdateCompleted);
			UtilitiesService.SurveySession_GetAllAnswersCompleted += new System.EventHandler<Utilities.SurveySession_GetAllAnswersCompletedEventArgs>(UtilitiesService_SurveySession_GetAllAnswersCompleted);

			// set
			this.SurveyObj = surveyObj;
			this.ConversationGuid = conversationGuid;
		}

		/// Explicit
		public Survey(
			EFS.RC.CC.CH.Entities.Surveys.SurveyInfo surveyObj,
			System.String documentId)
		{
			// check
			EFS.Common.Verify.Reference(surveyObj, "surveyObj");

			// init
			InitializeComponent();

			// register events
			UtilitiesService.SurveyCategory_GetBySurveyIDCompleted += new System.EventHandler<Utilities.SurveyCategory_GetBySurveyIDCompletedEventArgs>(UtilitiesService_SurveyCategory_GetBySurveyIDCompleted);
			UtilitiesService.SurveySessionData_CreateCompleted += new System.EventHandler<Utilities.SurveySessionData_CreateCompletedEventArgs>(UtilitiesService_SurveySessionData_CreateCompleted);
			UtilitiesService.SurveySessionData_UpdateCompleted += new System.EventHandler<Utilities.SurveySessionData_UpdateCompletedEventArgs>(UtilitiesService_SurveySessionData_UpdateCompleted);
			UtilitiesService.SurveySession_GetAllAnswersCompleted += new System.EventHandler<Utilities.SurveySession_GetAllAnswersCompletedEventArgs>(UtilitiesService_SurveySession_GetAllAnswersCompleted);

			// set
			this.SurveyObj = surveyObj;
			this.DocumentId = documentId;
		}

		/// Explicit
		public Survey(
			EFS.RC.CC.CH.Entities.Surveys.Sessions.SessionInfo surveySessionObj)
		{
			// check
			EFS.Common.Verify.Reference(surveySessionObj, "surveySessionObj");

			// init
			InitializeComponent();

			// register events
			UtilitiesService.SurveyCategory_GetBySurveyIDCompleted += new System.EventHandler<Utilities.SurveyCategory_GetBySurveyIDCompletedEventArgs>(UtilitiesService_SurveyCategory_GetBySurveyIDCompleted);
			UtilitiesService.SurveySessionData_CreateCompleted += new System.EventHandler<Utilities.SurveySessionData_CreateCompletedEventArgs>(UtilitiesService_SurveySessionData_CreateCompleted);
			UtilitiesService.SurveySessionData_UpdateCompleted += new System.EventHandler<Utilities.SurveySessionData_UpdateCompletedEventArgs>(UtilitiesService_SurveySessionData_UpdateCompleted);
			UtilitiesService.SurveySession_GetAllAnswersCompleted += new System.EventHandler<Utilities.SurveySession_GetAllAnswersCompletedEventArgs>(UtilitiesService_SurveySession_GetAllAnswersCompleted);
				
			// set
			this.SurveyObj = surveySessionObj.Survey;
			this.ConversationGuid = surveySessionObj.Session.ConversationGuid;
			this.DocumentId = surveySessionObj.Session.DocumentId;
			this.SurveySessionObj = surveySessionObj;
		}
		#endregion

		#region Properties
		/// Property SurveyObj: Get, Set
		public EFS.RC.CC.CH.Entities.Surveys.SurveyInfo SurveyObj { get; private set; }

		/// Property SurveySessionObj: Get, Set
		public EFS.RC.CC.CH.Entities.Surveys.Sessions.SessionInfo SurveySessionObj { get; private set; }

		/// Property ConversationGuid: Get, Set
		public System.Guid? ConversationGuid { get; private set; }

		/// Property DocumentId: Get, Set
		public System.String DocumentId { get; private set; }

		/// Property Answers: Get, Set
		public EFS.RC.CC.CH.Entities.Surveys.Sessions.AnswerInfo[] Answers { get; private set; }
		#endregion

		#region LoadData
		/// LOad survey
		private void LoadSurvey()
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Loading Categories for Survey {0}", SurveyObj.Name);

			// set text
			textBlockSurvey.Text = SurveyObj.Name;

			// switch review type
			switch (EFS.Common.Functions.Nullable<EFS.RC.CC.CH.Entities.Surveys.SurveyInfo.eReviewType>.GetSafe(SurveyObj.ReviewType, EFS.RC.CC.CH.Entities.Surveys.SurveyInfo.eReviewType.Agent))
			{
				case EFS.RC.CC.CH.Entities.Surveys.SurveyInfo.eReviewType.Customer:
					{
						gridStartStopContinue.Visibility = System.Windows.Visibility.Collapsed;
						break;
					}
				default:
					{
						break;
					}
			}

			if (SurveySessionObj != null)
			{
				UtilitiesService.SurveySession_GetAllAnswersAsync(SurveySessionObj.Session.ID.Value);
				startTextBox.Text = SurveySessionObj.Session.Survey_Start;
				stopTextBox.Text = SurveySessionObj.Session.Survey_Stop;
				continueTextBox.Text = SurveySessionObj.Session.Survey_Continue;
				DocumentId = SurveySessionObj.Session.DocumentId;

				if (SurveySessionObj.ReadOnly == true)
				{
					startTextBox.IsReadOnly = true;
					stopTextBox.IsReadOnly = true;
					continueTextBox.IsReadOnly = true;
					buttonSave.Visibility = System.Windows.Visibility.Collapsed;
					buttonCancel.Visibility = System.Windows.Visibility.Collapsed;
				}
			}
			else
			{
				// call ws
				UtilitiesService.SurveyCategory_GetBySurveyIDAsync(SurveyObj.ID.Value);
			}
		}

		/// Load categories
		private void LoadCategories(EFS.RC.CC.CH.Entities.Surveys.Category[] categories)
		{
			// check
			EFS.Common.Verify.Reference(categories, "categories");

			// make controls
			for (System.Int32 i = 0; i < categories.Length; ++i)
			{
				System.Windows.Thickness margin = new System.Windows.Thickness(0, 0, 0, 0);
				if (i > 0)
				{
					SleepBetweenRepetitiveAsyncCalls();
					margin = new System.Windows.Thickness(0, 7, 0, 0);
				}

				EFS.RC.Survey.Controls.Category controlCategory = new EFS.RC.Survey.Controls.Category(categories[i], this);
				controlCategory.Name = System.String.Format("controlCategory_{0}", categories[i].ID.Value);
				controlCategory.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
				controlCategory.VerticalAlignment = System.Windows.VerticalAlignment.Top;
				controlCategory.Margin = margin;
				stackPanelCategories.Children.Add(controlCategory);
			}

		}
		#endregion

		#region Utilities
		/// Validate
		public System.Boolean Validate()
		{
			// cicle all categories
			System.Boolean areCategoriesValid = true;
			foreach (EFS.RC.Survey.Controls.Category controlCategory in stackPanelCategories.Children)
			{
				if (!controlCategory.Validate())
				{
					areCategoriesValid = false;
				}
			}

			// ok
			return areCategoriesValid;
		}

		/// <summary>
		/// Calculate average and notify changes
		/// </summary>
		public void Calculate_AnswerClick()
		{
			double score = 0;
			double answerscore_ = 0;
			int answer_no = 0;

			foreach (EFS.RC.Survey.Controls.Category controlCategory in stackPanelCategories.Children)
			{
				// cicle all question controls
				foreach (EFS.RC.Survey.Controls.Question controlQuestion in controlCategory.stackPanelQuestions.Children)
				{
					// cicle all answer controls
					foreach (EFS.RC.Survey.Controls.Answer controlAnswer in controlQuestion.stackPanelAnswers.Children)
					{
						if (controlAnswer.IsSelected)
						{
							if (null != controlAnswer.AnswerObj.Score && controlAnswer.AnswerObj.Score.Value != -1)
							{
								answer_no = answer_no + 1;
								answerscore_ = answerscore_ + controlAnswer.AnswerObj.Score.Value;
							}
						}
						else
						{
							continue;
						}
					}
				}

			}

			// make average
			if (answerscore_ > 0)
			{
				score = answerscore_ / answer_no;
			}

			// notify
			if (null != OnAverageChange)
			{
				OnAverageChange(score);
			}
		}

		/// GetAnswers
		private EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer[] GetAnswers()
		{

			// create ret value
			System.Collections.Generic.List<EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer> retValue =
				new System.Collections.Generic.List<EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer>();

			// cicle all categories
			foreach (EFS.RC.Survey.Controls.Category controlCategory in stackPanelCategories.Children)
			{

				// cicle all question controls
				foreach (EFS.RC.Survey.Controls.Question controlQuestion in controlCategory.stackPanelQuestions.Children)
				{


					// cicle all answer controls
					foreach (EFS.RC.Survey.Controls.Answer controlAnswer in controlQuestion.stackPanelAnswers.Children)
					{
						if (!controlAnswer.IsSelected)
						{
							continue;
						}

						EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer sessionAnswerObj = new EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer();
						sessionAnswerObj.SurveyAnswerId = controlAnswer.AnswerObj.ID;
						sessionAnswerObj.Comment = controlQuestion.Comment;

						retValue.Add(sessionAnswerObj);
					}
				}
			}

			// ok
			return retValue.ToArray();
		}

		public void AnswerRadioButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			System.Windows.MessageBox.Show("Hello !");
		}
		/// GetSessionData
		private EFS.RC.Survey.Tools.Sessions.SessionData GetSessionData()
		{
			// create data
			EFS.RC.Survey.Tools.Sessions.SessionData sessionData = new EFS.RC.Survey.Tools.Sessions.SessionData();

			// Session
			sessionData.Session = new EFS.RC.CC.CH.Entities.Surveys.Sessions.Session();
			if (SurveySessionObj != null)
			{
				sessionData.Session.ID = SurveySessionObj.Session.ID;
			}
			sessionData.Session.SurveyId = SurveyObj.ID;
			sessionData.Session.Survey_Continue = this.continueTextBox.Text;
			sessionData.Session.Survey_Start = this.startTextBox.Text;
			sessionData.Session.Survey_Stop = this.stopTextBox.Text;
			sessionData.Session.ConversationGuid = ConversationGuid;
			sessionData.Session.DocumentId = DocumentId;

			// create answers
			System.Collections.Generic.List<EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer> answerList = new System.Collections.Generic.List<EFS.RC.CC.CH.Entities.Surveys.Sessions.Answer>();

			// add answers
			sessionData.Answers = GetAnswers();

			// ok
			return sessionData;
		}
		#endregion

		#region WS Callbacks

		/// SurveyCategory_GetBySurveyIDCompleted
		private void UtilitiesService_SurveyCategory_GetBySurveyIDCompleted(object sender, Utilities.SurveyCategory_GetBySurveyIDCompletedEventArgs e)
		{
			// close wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			try
			{
				// verify
				if (null != e.Error)
				{
					throw e.Error;
				}

				// deserialize
				EFS.RC.CC.CH.Entities.Surveys.Category[] categories =
					EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.CH.Entities.Surveys.Category[]>(e.Result.ToString());

				// show
				LoadCategories(categories);
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to retrieve categories.", ex);
			}
		}

		/// SurveySessionData_CreateCompleted
		private void UtilitiesService_SurveySessionData_CreateCompleted(object sender, Utilities.SurveySessionData_CreateCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			try
			{
				// verify
				if (null != e.Error)
				{
					throw e.Error;
				}

				// verify result
				EFS.Common.Verify.Condition(e.Result.HasValue, "e.Result.HasValue");

				// call delegates
				if (null != OnSaveCompleted)
				{
					OnSaveCompleted(e.Result.Value);
				}
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to create monitoring.", ex);
			}
		}

		/// UtilitiesService_SurveySessionData_UpdateCompleted
		private void UtilitiesService_SurveySessionData_UpdateCompleted(object sender, Utilities.SurveySessionData_UpdateCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			try
			{
				// verify
				if (null != e.Error)
				{
					throw e.Error;
				}

				// verify result
				EFS.Common.Verify.Condition(e.Result.HasValue, "e.Result.HasValue");

				// call delegates
				if (null != OnSaveCompleted)
				{
					OnSaveCompleted(e.Result.Value);
				}
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to update monitoring.", ex);
			}
		}

		// UtilitiesService_SurveySession_GetAllAnswersCompleted
		void UtilitiesService_SurveySession_GetAllAnswersCompleted(object sender, Utilities.SurveySession_GetAllAnswersCompletedEventArgs e)
		{
			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.Completed(this);

			try
			{
				// verify
				if (null != e.Error)
				{
					throw e.Error;
				}

				// deserialize
				EFS.RC.CC.CH.Entities.Surveys.Sessions.AnswerInfo[] answers =
					EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.CH.Entities.Surveys.Sessions.AnswerInfo[]>(e.Result.ToString());

				this.Answers = answers;

				// call ws
				UtilitiesService.SurveyCategory_GetBySurveyIDAsync(SurveyObj.ID.Value);
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to retrieve data.", ex);
			}
		}
		#endregion

		#region Events
		/// Saves the survey
		private void buttonSave_Click(object sender, System.Windows.RoutedEventArgs e)
		{

			// show wait DLG
			EFS.Common.UI.Controls.NotificationDialog.ProgressDialog.InProgress(this, "Saving your survey");

			if (SurveySessionObj != null)
			{
				// save
				UtilitiesService.SurveySessionData_UpdateAsync(EFS.Common.Serialization.Functions.SerializeToString(GetSessionData()));
			}
			else
			{
				// save
				UtilitiesService.SurveySessionData_CreateAsync(EFS.Common.Serialization.Functions.SerializeToString(GetSessionData()));
			}
		}

		//cancel the survey

		private void buttonCancel_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			// call delegates
			if (null != OnCancel)
			{
				OnCancel();
			}
		}

		/// LOaded
		private void ControlSurvey_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			LoadSurvey();
		}

		#endregion
	}

}